import requests
import json,hashlib
from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()



class WechatAPI():

    def __init__(self, appid, appsecret):
        self.appid = appid
        self.appsecret = appsecret


    def login(self, code):

        token = self.login_token(code)
        return self.user_info_from_wechat(token)


    def login_token(self, code):
        """
        获取登陆token
        """
        params = {
            'appid': self.appid,
            'secret': self.appsecret,
            'code':code,
            'grant_type': 'authorization_code'
        }
        url = 'https://api.weixin.qq.com/sns/oauth2/access_token'
        response = requests.get(url, params=params)
        result = json.loads(bytes.decode(response.content), encoding='utf-8')
        return result

    def user_info_from_wechat(self, token):
        """
        通过token从微信获取用户信息
        :param token:
        :return:
        """
        params = {
            'access_token': token['access_token'],
            'openid': token['openid'],
            'lang': 'zh_CN'
        }
        url = 'https://api.weixin.qq.com/sns/userinfo'
        response = requests.get(url, params=params)
        result = json.loads(bytes.decode(response.content), encoding='utf-8')
        return result




    def work_share(self,nonceStr, timestamp, url):
        if cache.get('ticket') is not None:
            ticket = cache.get('ticket')
            return self.getSHA1Str(ticket,nonceStr, timestamp, url)
        else:
            ticket = self.get_ticket()
            return self.getSHA1Str(ticket,nonceStr, timestamp, url)

    def get_ticket(self):
        # 通过APPID和appssecret获取access_token然后取出ticket
        response = requests.get(
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}".format(self.appid,
                                                                                                               self.appsecret))
        content = json.loads(bytes.decode(response.content), encoding='utf-8')
        access_token = content['access_token']
        if access_token is None:
            return '不存在'
        url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={0}&type=jsapi'.format(access_token)
        content = requests.get(url).json()
        ticket = content['ticket']
        if ticket is None:
            return '不存在'
        cache.set('ticket', ticket, timeout=2 * 60 * 60 - 5)
        response.close()
        return ticket

    def getSHA1Str(self,jsapi_ticket, nonceStr, timestamp, url):
        encodeStr = "jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}".format(jsapi_ticket, nonceStr, timestamp, url)
        sha1 = hashlib.sha1()
        sha1.update(encodeStr.encode('utf-8'))
        res = sha1.hexdigest()
        return res























